package com.zlp.spring.mybatis.spring;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
 * 自定义扫包注册到SpringBeanDefinition
 * @date: 2022/2/22 20:06
 * @return: 
 */
public class MyMapperScannerRegistrar implements ImportBeanDefinitionRegistrar {


    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MyMapperScan.class.getName()));
        List<String> basePackages = new ArrayList<>();
        basePackages.addAll(
                Arrays.stream(annoAttrs.getStringArray("value")).
                        filter(StringUtils::hasText).collect(Collectors.toList())
        );
        System.out.println(basePackages);
        for (String basePackage : basePackages) {
            ClassLoader classLoader = MyMapperScannerRegistrar.class.getClassLoader();
            String classPath = basePackage.replace(".", "/");
            URL resource = classLoader.getResource(classPath);
            // 获取扫描包绝对路径地址
            File files = new File(resource.getPath());
            if (files.isDirectory()) {
                // 获取扫描包路径下面 class 集合
                File[] listFiles = files.listFiles();
                for (File file : listFiles) {
                    if (file.isDirectory()) {
                        for (File file1 : file.listFiles()) {
                            registryBeanFinition(registry, classLoader, file1);
                        }
                    }
                    registryBeanFinition(registry, classLoader, file);
                }
            }
        }

    }

    private void registryBeanFinition(BeanDefinitionRegistry registry, ClassLoader classLoader, File file) {
        String absolutePath = file.getAbsolutePath();
        if (absolutePath.contains(".class") && absolutePath.contains("com") ) {
            String calssName = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
            calssName = calssName.replace("\\", ".");
            try {
                Class<?> clazz = classLoader.loadClass(calssName);
                String simpleName = lowerFirstCase(clazz.getSimpleName());
                // 生成代理对象
                BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(MyMapperFactoryBean.class);
                GenericBeanDefinition genericBeanDefinition = (GenericBeanDefinition) beanDefinitionBuilder.getBeanDefinition();
                registry.registerBeanDefinition(simpleName,genericBeanDefinition);
                // 注入方式->构造方法注入
                genericBeanDefinition.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
                genericBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(calssName);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 首字母小写方法，大写会变成小写，如果小写首字母会消失
     * @param str
     * @date: 2022/2/22 19:55
     * @return: java.lang.String
     */
    public String lowerFirstCase(String str){
        char[] chars = str.toCharArray();
        chars[0] +=32;
        return String.valueOf(chars);
    }


}
